﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Reflection;
using System.Web;
using Wantn.Share;

namespace App.Sdx.Api
{
    internal sealed class DAL
    {
        private static DAL OWNER;

        private DBAccess<SQLiteConnection, SQLiteDataAdapter, SQLiteParameter> _dbAccess;

        public static DAL Instance
        {
            get
            {
                if (DAL.OWNER == null)
                {
                    DAL.OWNER = new DAL();
                }
                return DAL.OWNER;
            }
        }

        private DAL()
        {

            this._dbAccess = null;

        }

        public void Open()
        {
            if (this._dbAccess == null)
            {
                this._dbAccess = new DBAccess<SQLiteConnection, SQLiteDataAdapter, SQLiteParameter>(this.Connection, 0);
            }
        }

        public void Close()
        {
            if (this._dbAccess != null)
            {
                this._dbAccess = null;
            }
        }

        private string Connection
        {
            get
            {
                string text = "";
                try
                {
                    string rootPath = HttpContext.Current.Server.MapPath("~");
                    text = Path.Combine(AppInfo.GetAppDir(Assembly.GetExecutingAssembly()), "DataBase.db");
                    text = "data source=" + text + ";";
                }
                catch
                {
                }
                return text;
            }
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable GetDataTable(string sql)
        {
            return this._dbAccess.ExecQuery(sql).Tables[0];
        }

        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public bool ExecSQL(string sql)
        {
            return this._dbAccess.ExecSQL(sql) > 0;
        }
    }
}